package cn.lau.demo.util;

import cn.lau.demo.pojo.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @author War horse imwarhorse@aliyun.com
 * Date: 2020/12/23
 * Description: JWT(Json Web Token)工具类
 * 包含token签发、token校验、token过期时间校验、token续签等方法
 */
public class JWTUtil {

	/* token有效时间。6h */
	private final static long EXPIRED_TIME = 6 * 60 * 60 * 1000;
	/* Token密钥 */
	private final static String SECRET = "1p3t2q";
	/* Token签发者 */
	private final static String ISSUER = "shiro-jwt";

	/* 向外提供，token在客户端发起请求时作为什么字段名的值 */
	public final static String TOKEN_HEADER = "Authorization";

	public static String sign(User user) {
		return JWT.create()
				.withClaim("username", user.getUsername())
				.withClaim("id", user.getId())
				.withIssuer(ISSUER)
				.withIssuedAt(new Date())
				.withExpiresAt(new Date(System.currentTimeMillis() + EXPIRED_TIME))
				.sign(Algorithm.HMAC256(SECRET));
	}

	/**
	 * 校验token是否合法
	 * @param token
	 * @return
	 */
	public static boolean verify(String token) {
		try {
			Algorithm algorithm = Algorithm.HMAC256(SECRET);
			JWTVerifier verifier = JWT.require(algorithm)
					.withIssuer(ISSUER)
					.build();
			DecodedJWT jwt = verifier.verify(token);
			return true;
		} catch (IllegalArgumentException | JWTVerificationException e) {
			return false;
		}
	}

	public static String getUsername(String token) {
		if (token == null) return null;
		if (verify(token)) {
			try {
				DecodedJWT jwt = JWT.decode(token);
				return jwt.getClaim("username").asString();
			} catch (JWTDecodeException e) {
				return null;
			}
		}
		return null;
	}

}
